<template>
  <div class="common-list-container__v2 project-manage-list-container column">
    <!-- start 头部搜索栏 -->
    <div class="header-container">
      <div class="common-list-header__v2">
        <div class="flex-1">
          <el-dropdown trigger="click" @command="handleChangeViewType">
            <span class="el-dropdown-link">
              {{ currentViewTitle }} <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="(mode, index) in viewTypeList" :key="index" :command="mode.value">{{ mode.label }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <!-- <span class="set-field-btn" v-show="allowSetFields" @click="handleSelectColumn"><i class="iconfont icon-setting"></i></span> -->
        </div>

        <div class="flex-x base-search-group input-with-append-search">
          <el-input
            v-model.trim="searchParams.likeSearch"
            :placeholder="$t('common.placeholder.searchProjectManage')"
            prefix-icon="el-icon-search"
            @keyup.enter.native="handleSearch"
          >
            <el-button type="primary" slot="append" @click="handleSearch">{{$t('common.base.search')}}</el-button>
          </el-input>
          <el-button class="ml_12" type="plain-third" @click="handleReset">{{$t('common.base.reset')}}</el-button>

          <advanced-search
            ref="advancedSearchRef"
            :fields="advanceSearchColumns"
            :has-create="false"
            :has-save="false"
            :search-model="viewportSearchModel"
            :in-common-use="inCommonUse"
            @changeCommonUse="changeCommonUse($event, advancedSearchCommonUseStorageKey)"
            @search="handleAdvancedSearch"
          />
        </div>
      </div>

      <div class="base-filter-tag-list-container" v-show="packUp">
        <BaseFilterTagList
          :label="$t('common.projectManage.projectTypeName')+':'"
          :active="searchParams.templateId"
          :list="projectTypes"
          @choose="handleFilterClick($event, 'templateId')"
        ></BaseFilterTagList>

        <template v-if="!isCardMode">
          <BaseFilterTagList :label="$t('projectManage.setting.projectStatus.title')+':'" :active="searchParams.projectStatusType" :list="dataStatusList" @choose="handleFilterClick($event, 'projectStatusType')">
            <template v-slot="{ label, number, children }">
              {{ label }} ({{ number }})
              <i
                v-if="children && children.length"
                :class="['iconfont', !customStatusCollaspe ? 'icon-Icon_up' : 'icon-more']"
                @click.stop="customStatusCollaspe = !customStatusCollaspe"
              ></i>
            </template>
          </BaseFilterTagList>

          <!-- 自定义状态 -->
          <div class="custom-status-filter-container" v-show="customStatusList.length && !customStatusCollaspe">
            <el-checkbox-group v-model="searchParams.projectStatusId" @change="handleFilterClick({ value: $event }, 'projectStatusId')">
              <el-checkbox v-for="child in customStatusList" :label="child.id" :key="child.id">
                <span>{{ child.name }}</span>&nbsp;({{ child.number }})
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </template>

        <!-- 创建视角 -->
        <BaseFilterTagList :label="$t('common.base.createAngle')+':'" :active="searchParams.searchType" :list="createViewList" @choose="handleFilterClick($event, 'searchType')"></BaseFilterTagList>
        <!-- 标签 -->
        <BaseFilterTagList v-if="labelGray" :label="$t('common.label.tag')+':'" :active="searchParams.delayType" :list="projectLabelsList" @choose="handleFilterClick($event, 'delayType')"></BaseFilterTagList>
      </div>
    </div>
    <!-- end 头部搜索栏 -->

    <div class="bbx-normal-pack-up">
      <div @click="packUp = !packUp">
        <i :class="['iconfont', packUp ? 'icon-Icon_up' : 'icon-more']"></i>
      </div>
    </div>

    <div class="project-manage-list-container-content">
      <component
        ref="currentComponentRef"
        :is="currentView"
        :columns="columns"
        :btnAuth="btnAuth"
        :params="searchParams"
        :statusList="dataStatusList"
        :projectTypeList="projectTypeList"
        @handleSelectColumn="handleSelectColumn"
        :packUp="packUp"
      ></component>
    </div>

    <!-- start 选择列 -->
    <biz-select-column
      ref="bizSelectColumnComponent"
      :max="selectColumnMax"
      :mode="tableName"
      :validate="validateColumn"
      @save="saveSelectColumns($event, selectColumnStorageKey)"
    />
    <!-- end 选择列 -->
  </div>
</template>

<script>
/* components */
import AdvancedSearch from '@src/component/AdvancedSearch/index.vue';
import ProjectTableList from '@src/modules/projectManage/projectManageList/components/ProjectTableList.vue';
import ProjectTimeList from '@src/modules/projectManage/projectManageList/components/ProjectTimeList.vue';
import ProjectCardList from '@src/modules/projectManage/projectManageList/components/ProjectCardList.vue';
/* model */
import { PROCESS_CODE, ViewTypeComponentNameEnum, selectColumnMaxMap, viewTypeList, createViewList, projectLabelsList, projectManageViewTypeValue } from '@src/modules/projectManage/projectManageList/model';
/* enum */
import StorageKeyEnum from '@model/enum/StorageKeyEnum';
import TableNameEnum from '@model/enum/TableNameEnum';
/* util */
import { getColumnFields, saveDataToStorage, getDataToStorage } from '@src/modules/projectManage/projectManageList/util';
import { message } from '@src/util/message';
import { t } from '@src/locales';
import _ from 'lodash';
import Log from '@src/util/log';
import { getRootWindow } from '@src/util/dom';
/* hooks */
import { useSelectColumn } from '@src/modules/projectManage/projectManageList/hooks/useSelectColumn';
import { useAdvancedSearch } from '@src/modules/projectManage/projectManageList/hooks/useAdvancedSearch';
import { useFetchProjectTypeList, useFetchProjectFieldList, useFetchProjectStatusList, useFetchProjectAuthButton } from '@src/modules/projectManage/projectManageList/hooks/useFetch';
/* vue */
import { ref, onMounted, reactive, computed, watch } from 'vue';

export default {
  name: 'project-manage-list-page',
  components: {
    AdvancedSearch,
    [ProjectTableList.name]: ProjectTableList,
    [ProjectTimeList.name]: ProjectTimeList,
    [ProjectCardList.name]: ProjectCardList,
  },
  setup(props, {}) {
    // 选择列
    const { columns, buildSelectColumns, saveSelectColumns } = useSelectColumn();
    // 高级搜索列
    const { viewportSearchModel, inCommonUse, advanceSearchColumns, buildAdvancedColumns, changeCommonUse, recoverCommonUse } = useAdvancedSearch();

    // 项目管理数据
    const { projectTypeList, fetchProjectTypeList } = useFetchProjectTypeList();
    const { fields, fetchProjectFieldList } = useFetchProjectFieldList();
    const { dataStatusList, fetchProjectStatusList } = useFetchProjectStatusList();
    const { btnAuth, fetchProjectAuthButton } = useFetchProjectAuthButton();

    // 表名
    const tableName = ref(TableNameEnum.Project);
    // 高级搜索ref
    const advancedSearchRef = ref(null);
    // 选择列ref
    const bizSelectColumnComponent = ref(null);
    const bizTimeSelectColumnComponent = ref(null);
    // 当前视图组件ref
    const currentComponentRef = ref(null);
    // 自定义状态展开折叠
    let customStatusCollaspe = ref(true);
    // 收起折叠
    let packUp = ref(true);

    // 当前视图
    let currentView = ref(ViewTypeComponentNameEnum.Time);
    // 当前视图标题
    const currentViewTitle = computed(() => viewTypeList.find(mode => mode.value === currentView.value)?.label);
    // 允许设置显示字段
    let allowSetFields = computed(() => currentView.value === ViewTypeComponentNameEnum.Card);
    // 是否是卡片模式
    const isCardMode = computed(() => currentView.value === ViewTypeComponentNameEnum.Card);
    // 自定义的状态列表
    const customStatusList = computed(() => dataStatusList.value.find(item => item.code == PROCESS_CODE)?.children || []);
    // 选择列缓存key
    const selectColumnStorageKey = computed(() => `${currentView.value}_${searchParams.templateId}_select_column`);
    // 高级搜索常用字段
    const advancedSearchCommonUseStorageKey = ref(StorageKeyEnum.ProjectManageListAdvancedSearchCommonUseFields);
    // 选择列可选字段个数限制
    const selectColumnMax = computed(() => selectColumnMaxMap[currentView.value]);
    // 项目类型
    const projectTypes = computed(() => {
      const origin = _.cloneDeep(projectTypeList.value);

      // 非卡片模式 增加“全部”选项
      if (!isCardMode.value) origin.unshift({ value: '', label: t('common.base.all') });
      
      return origin;
    })

    // 标签灰度
    const labelGray = computed(() => {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.PROJECT_DELAY || false
    })

    // 视图参数
    const viewParams = computed(() => {
      const viewTypeObj = {
        [ViewTypeComponentNameEnum.Table]: 1,
        [ViewTypeComponentNameEnum.Time]: 2,
        [ViewTypeComponentNameEnum.Card]: 3,
      }

      return viewTypeObj[currentView.value]
    }) 

    // 构建搜索参数
    const buildParams = () => {
      // 卡片视图重置，仍然保留选中第一个项目类型
      return {
        templateId: isCardMode.value ? (projectTypes.value[0]?.id) : '',
        likeSearch: '',
        searchType: 'ALL',
        delayType: '0',
        projectStatusType: '',
        projectStatusId: [],
        conditions: [],
        systemConditions: [],
        viewType: viewParams.value
      }
    }

    // 搜索参数
    let searchParams = reactive(buildParams());

    // 构建选择列
    const buildColumns = () => {
      const originFields = getColumnFields(fields.value, currentView.value);
      buildSelectColumns(originFields, selectColumnStorageKey.value);
    }

    // 验证选择列
    const validateColumn = (columns) => {
      if(selectColumnMax.value && columns.length > selectColumnMax.value) {
        message.error(t('common.connector.maxFieldsLength', {length: selectColumnMax.value}));
        return false;
      }
      
      return true;
    }

    // 切换列表视图模式
    const handleChangeViewType = (mode) => {
      currentView.value = mode;

      // 看板视图 未选择项目类型时默认第一个
      setCardList();

      // 构建选择列数据
      buildColumns();
      // 缓存当前视图
      setViewTypeValue();
    };

    // 初始化视图模式
    const initViewType = async () => {
        try {
          const viewType = await getDataToStorage(projectManageViewTypeValue);

          if(viewType) {
            currentView.value = viewType;
            setCardList();
          };
        } catch (error) {
          Log.error(error, '获取初始化视图模式');
          return Promise.reject(error);
        }
    }

    // 设置视图缓存
    const setViewTypeValue = async () => {
        saveDataToStorage(projectManageViewTypeValue, currentView.value);
    }

    // 看板视图 未选择项目类型时默认第一个
    const setCardList = () => {
      searchParams['viewType'] = viewParams.value
      if (isCardMode.value) {
        searchParams.templateId = searchParams.templateId || projectTypes.value[0]?.id;
        searchParams.projectStatusType = '';
        searchParams.projectStatusId = [];
        fetchProjectStatusList(searchParams);
      } else {
        fetchProjectStatusList(searchParams);
      }
    }
    
    // 选择列
    const handleSelectColumn = () => {
      bizSelectColumnComponent.value?.open(columns.value);
    };

    // 视图筛选搜索
    const handleFilterClick = ({ value }, key) => {
      searchParams[key] = value;

      // 项目类型: 重置高级搜索条件
      if (key === 'templateId') {
        fetchProjectStatusList(searchParams);
      }

      // 数据状态: 非进行中时 重置自定义状态
      if (key == 'projectStatusType' && value != PROCESS_CODE) {
        searchParams.projectStatusId = [];
        customStatusCollaspe.value = true;
      }

      // 自定义状态: 若非进行中则切换至进行中
      if (key == 'projectStatusId' && searchParams.projectStatusType != PROCESS_CODE) {
        searchParams.projectStatusType = PROCESS_CODE;
      }
      
      if (key == 'searchType') {
        fetchProjectStatusList(searchParams);
      }
      handleSearch();
    };

    // 重置高级搜索条件
    const resetAdvancedConditions = () => {
      // 需求：切换快捷条件 高级搜索内保留条件但是搜索不携带
      searchParams.conditions = [];
      searchParams.systemConditions = [];

      advancedSearchRef.value?.setButtonStatus(false);
    }

    // 搜索
    const handleSearch = ()=> {
      currentComponentRef.value?.search(true);
    }

    // 重置搜索
    const handleReset = () => {
      Object.assign(searchParams, buildParams());

      // 重置高级搜索：会触发高级搜索事件handleAdvancedSearch
      viewportSearchModel.value = [];
    }

    // 高级搜索
    const handleAdvancedSearch = (searchModel) => {
      // TODO 暂时处理
      const timeData = ['planStartTime', 'planEndTime', 'createTime', 'completeTime'];
      const { conditions = [], systemConditions = [] } = searchModel;

      systemConditions.forEach(x => {
        if(timeData.includes(x.property)) {
          x.betweenValue1 = new Date(x.betweenValue1).getTime();
          x.betweenValue2 = new Date(x.betweenValue2).getTime();
        }
      })

      searchParams.conditions = conditions;
      searchParams.systemConditions = systemConditions;
      
      handleSearch();
    }

    // 修改搜索列的key
    const setFieldName = (fields = []) => {
      const obj = {
        'createUser': 'createUid',
      }

      return fields.map(x => { 
        x.fieldName = obj[x?.fieldName] || x?.fieldName;

        return x;
      })
    }

    // 初始化项目类型字段
    const initializeProjectTypeFields = async() => {
      // 获取项目类型字段
      await fetchProjectFieldList(searchParams.templateId);
      // 合并本地缓存列数据
      buildColumns();
      // 构建高级搜索列
      buildAdvancedColumns(setFieldName(fields.value));
    }

    onMounted(async () => {
      // 恢复常用
      recoverCommonUse(advancedSearchCommonUseStorageKey.value);
      // 获取按钮权限
      fetchProjectAuthButton();
      // 获取项目类型
      await fetchProjectTypeList();
      // 获取项目状态
      fetchProjectStatusList(searchParams);
      // 初始化项目字段
      initializeProjectTypeFields();
      // 初始化视图
      initViewType();
      // [tab_spec]标准化刷新方式
      window.__exports__refresh = async () => {
        setTimeout(() => {
          handleSearch()
        }, 1000)
      }
    });

    // 监听项目类型变化
    watch(() => searchParams.templateId, (newValue) => {
      // 初始化项目字段
      initializeProjectTypeFields();
      // 重置高级搜索条件
      resetAdvancedConditions();
    })

    return {
      packUp,
      isCardMode,
      customStatusCollaspe,
      allowSetFields,
      viewTypeList,
      createViewList,
      projectLabelsList,
      dataStatusList,
      currentView,
      currentViewTitle,
      customStatusList,
      currentComponentRef,
      selectColumnStorageKey,
      advancedSearchCommonUseStorageKey,

      projectTypeList,
      projectTypes,
      labelGray,
      fields,
      columns,
      searchParams,
      selectColumnMax,
      btnAuth,

      inCommonUse,
      viewportSearchModel,
      advanceSearchColumns,
      bizSelectColumnComponent,
      bizTimeSelectColumnComponent,
      tableName,
      advancedSearchRef,

      handleSearch,
      handleReset,
      handleFilterClick,
      handleChangeViewType,
      
      changeCommonUse,
      handleAdvancedSearch,

      validateColumn,
      saveSelectColumns,
      handleSelectColumn,
    };
  },
};
</script>

<style lang="scss" scoped>
@import "@src/assets/scss/common-list.scss";

.project-manage-list-container {
  
  .common-list-header__v2 {
    border-radius: 4px 4px 0 0 !important;

    .el-dropdown-link {
      color: $text-color-primary;
      cursor: pointer;
    }

    .set-field-btn {
      padding-left: 12px;
      margin-left: 12px;
      border-left: 1px solid $color-border-l1;

      .iconfont {
        font-size: $font-size-base;
        color: $text-color-regular;
        cursor: pointer;
      }
    }
  }
  .base-filter-tag-list-container {
    background: #fff;
    border-radius: 0 0 4px 4px;
    padding: 0 16px 16px;

    .base-filter-tag-list__tag {
      .iconfont {
        font-size: $font-size-small;
        color: $text-color-regular;
        margin-left: 4px;
      }
    }

    .custom-status-filter-container {
      margin-bottom: 12px;

      ::v-deep .el-checkbox-group {
        padding-left: 106px;
        display: flex;
        flex-wrap: wrap;

        .el-checkbox {
          max-width: 256px;
          height: 22px;
          padding: 0 12px;
          margin-right: 0;

          color: $text-color-secondary;
          font-size: 0;
          font-weight: normal;

          display: inline-flex;
          align-items: center;

          &__label {
            flex: 1;
            font-size: 13px;
            display: flex;
            overflow: hidden;

            span {
              flex: 1;
              @include text-ellipsis();
            }

            &:hover {
              color: $color-primary;
            }
          }
        }
      }
    }
  }

  &-content {
    flex: 1;
    overflow: hidden;
  }
}
.project-manage-list-container-content{
  height:100%;
  .common-list-view__v2{
    height:100%;
  }
}
</style>